package com.totoro.controller;

import com.totoro.pojo.User;
import com.totoro.service.UserService;
import com.totoro.utils.MailUtil;
import com.totoro.utils.PhoneUtil;
import com.totoro.utils.ToolSecurityPwd;
import com.totoro.utils.TotoroUtils;
import lombok.SneakyThrows;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author TOTORO
 * @date 2021/4/25 21:18
 * 注册控制器
 */
@Controller
@RequestMapping("/register")
public class RegisterFormController {
    private static final String CODE_PAGE = "/public_page/accept_code.jsp";
    static Logger logger = Logger.getLogger(RegisterFormController.class);
    private static String emailRandom = "";

    @Autowired
    private UserService usi;

    /**
     * 执行手机验证码方法
     * @param phone
     * @param response
     * @return
     */
    @RequestMapping(value = "/send_code", method = RequestMethod.POST)
    public String sendCode(@RequestParam("phone") String phone, HttpServletResponse response) {
        // 生成六位数随机数当作效验码
        int phoneCode = new Random().nextInt(899999)+100000;
        // 调用发送验证码方法
        String msg = PhoneUtil.getPhoneCode(phone, phoneCode);
        // 将手机和验证码存进cookie，时限为15分钟
        Cookie cookie = new Cookie(phone,phoneCode+"");
        cookie.setMaxAge(15*60);
        cookie.setPath("/");
        response.addCookie(cookie);
        return "forward:/public_page/accept_code.jsp";
    }

    /**
     * 手机注册时保存手机至session，通过混搭数获取手机号。
     * @param phone
     * @param session
     * @return
     */
    @RequestMapping("/save_info")
    public String saveUserPhone(@RequestParam("phone") String phone, HttpSession session){
        // 获取手机，进行判断
        if(StringUtils.isEmpty(phone)){
            return "redirect:404.html";
        }
        session.setMaxInactiveInterval(900);
        // 获取随机数，进行保护
        String random = "0"+TotoroUtils.getRandomChar(25);
        session.setAttribute(random,phone);
        return "redirect:/register_02_user_info_"+random+".htm";
    }

    /**
     * 邮箱注册时的手机号存进session，修改时方便根据该手机查询，并返回一个jsp页面的内容给前端
     * @param regPhone
     * @param session
     * @return
     */
    @RequestMapping(value = "/set_rp", method = RequestMethod.POST)
    public String setRegPhone(@RequestParam("regPhone") String regPhone, HttpSession session){
        session.setAttribute("regPhone", regPhone);
        return "forward:/user_process/email_mobile.jsp";
    }

    /**
     * 注册用户名是否重复
     * @param name
     * @return data [返回Json]
     */
    @ResponseBody
    @RequestMapping("/name_test")
    public String userNameTest(@RequestParam("name") String name){
        String data = null;
        // 获取前端传过来的用户名，数据库用户名，判断是否存在
        List recommend = new ArrayList();
            int flag = usi.userNameTest(name).size();
            if(flag>0){
                while(true){
                    String number = TotoroUtils.getRandomNickname(9);
                    if(usi.userNameTest(name+number).size()<=0){
                        recommend.add(name+number);
                        break;
                    }
                }
                while(recommend.size()<3){
                    String number = TotoroUtils.getRandomNickname(10);
                    if(usi.userNameTest(name+number).size()<=0){
                        recommend.add(name+number);
                    }
                }
                // 前端需要的数据
                data = "{'flag':'"+flag+"','u1':'"+recommend.get(0)+"','u2':'"+recommend.get(1)+"','u3':'"+recommend.get(2)+"'}";
            } else{
                data = "{'flag':'-1'}";
            }
        return data;
    }

    /**
     * 处理注册
     * @param type
     * @param phoneOrEmail
     * @param password
     * @param name
     * @param session
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam("type") String type, @RequestParam("phone")String phoneOrEmail, @RequestParam("password")String password,
                           @RequestParam("payPassword") String payPassword, @RequestParam("vipName")String name, HttpSession session){
            // 将密码进行加密，获取密码盐
            String salt = ToolSecurityPwd.generateSalt();
            //获取加密后的密文
            String newPassWord = ToolSecurityPwd.getEncryptedPassword(password, salt);
            // 打包成实体对象
            User user = new User();
            user.setUserName(name);
            user.setPhone(phoneOrEmail);
            user.setPassword(newPassWord);
            user.setSalt(salt);
            // 将密码支付进行加密，获取密码盐
            String paySalt = ToolSecurityPwd.generateSalt();
            //获取加密后的密文
            String newPassWord2 = ToolSecurityPwd.getEncryptedPassword(payPassword, paySalt);
            user.setPayPassword(newPassWord2);
            user.setPaySalt(paySalt);
        // 通过type区别是新用户注册（添加） 还是老用户使用邮箱注册（修改）
            if("0".equals(type)){
                int flag = usi.addUser(user);
            } else if("1".equals(type)){
                String regPhone = (String) session.getAttribute("regPhone");
                if(StringUtils.isEmpty(regPhone)){
                    return "@500.html";
                }
                user.setPhone(regPhone);
                user.setEmail(phoneOrEmail);
                usi.updateUser(user);
            }
        session.setMaxInactiveInterval(1500);
        session.setAttribute("regUser", user);
        return "redirect:/register_03_succeed.htm";
    }

    /**
     * 比较手机号是否存在
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/contrast_phone", method = RequestMethod.POST)
    public String contrastPhone(@RequestParam("phone") String phone){
        // 获取前端传过来的手机号，如果不存在，返回"isHave":false,如果存在，返回true，并提供数据
        boolean flag = usi.userInfoToPhone(phone).size()>0;
        String jsonStr = null;
        if(flag){
            // 如果有该手机号，收集信息
            User user = usi.userInfoToPhone(phone).get(0);
            String head = user.getHead();
            String name = user.getUserName();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("ishave",true);
            jsonObject.put("head",head);
            jsonObject.put("name",name);
            jsonObject.put("phone",phone);
            jsonStr = jsonObject.toString();
        } else{
            jsonStr = "{'ishave':false}";
        }
        return jsonStr;
    }

    /**
     * 发送邮件至用户邮箱
     * @param email
     * @param session
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/sent_email", method = RequestMethod.POST)
    public String sendEmail(@RequestParam("email") String email, HttpSession session){
        // 获取随机混搭数
        String random = "1"+TotoroUtils.getRandomChar(25);
        // 将数据保存在session中，
        // 每次注册新用户发送邮箱时，先清除该之前的邮箱session
        session.removeAttribute(emailRandom);
        session.setMaxInactiveInterval(900);
        session.setAttribute(random,email);
        // 调用发送邮件方法
        MailUtil.sendMail(email, random, 1, null);
        emailRandom = random;
        // 转发至发送成功页面，返回html给前端使用
        return "forward:/user_process/email_sent.jsp";
    }
}
